package com.sam;

import java.util.Stack;

/**
 * 波兰式是在通常的表达式中，二元运算符总是置于与之相关的两个运算对象之前，所以，这种表示法也称为前缀表达式
 * Created by samwang on 2017/11/24.
 */
public class PolishNotation {
    public static void main(String[] args) {
        //示例：+ * + 11 12 * + 24 35 88表示(11+12)*(24+35)
        //单个数的值等于自己
        exp("* + 11 12 + 24 35");
    }

    static void exp(String notation) {
        String[] s = notation.split(" ");
        int result = exp(s);
        System.out.println(notation + " = " + result);
    }

    static int exp(String[] strings) {
        Stack<String> stack = new Stack<>();
        for (String s : strings) {
            pushStack(s, stack);
        }

        return Integer.valueOf(stack.pop());

    }

    static void pushStack(String s,Stack<String> stack) {
        if (stack.empty()) {
            stack.push(s);
            return;
        }
        switch (s) {
            case "+":
            case "-":
            case "*":
            case "/":
                stack.push(s);
                break;
            default:
                if (stack.peek().matches("[\\+\\-\\*\\/]{1}")) {
                    stack.push(s);
                } else {
                    int a = Integer.valueOf(stack.pop());
                    int b = Integer.valueOf(s);
                    String option = stack.pop();
                    int result = 0;
                    switch (option) {
                        case "+":
                            result = a + b;
                            break;
                        case "-":
                            result = a - b;
                            break;
                        case "*":
                            result = a * b;
                            break;
                        case "/":
                            result = a / b;
                            break;
                        default:
                            throw new RuntimeException("表达式格式错误");
                    }
                    pushStack(String.valueOf(result), stack);

                }
        }
    }

}
